package com.ruoyi.api.yh.user;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONArray;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.ruoyi.api.yh.version.ApiVersion;
import com.ruoyi.common.config.ApiConfig;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.WxConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.RedisConstant;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.yh.api.R;
import com.ruoyi.common.yh.api.WeixinInit;
import com.ruoyi.common.yh.api.aop.LoginRequired;
import com.ruoyi.common.yh.api.dtovo.user.UserInfoVO;
import com.ruoyi.common.yh.api.dtovo.user.WeiXinNickNameDTO;
import com.ruoyi.common.yh.api.util.ApiUserUtils;
import com.ruoyi.framework.web.service.api.ApiLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserApiController
 * @Deacription cmm
 * @Date 2021/3/3 15:50
 * @Version 1.0
 **/
@ApiSupport(order = 2)
@Api(tags="用户API")
@RestController
@ApiVersion(1)
@RequestMapping("/{version}/app-api/user")
public class UserApiController {
    @Autowired
    private Validator validator;

    @Autowired
    private Mapper dozerMapper;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ApiConfig apiConfig;
    @Autowired
    private ApiLoginService apiLoginService;
    @ApiOperationSupport(author = "chenmingming",order = 1)
    @ResponseBody
    @ApiOperation(value = "获取个人用户信息")
    @LoginRequired
    @GetMapping("/getUserInfo")
    public R<UserInfoVO> getUserInfo() {

        UserInfoVO userInfoVO=new UserInfoVO();
        SysUser businesTUser= ApiUserUtils.getBusinesTUserr();
        businesTUser=apiLoginService.selectTUserById(businesTUser.getUserId());
        if(businesTUser==null){
            throw new CustomException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
        }
        /**
         * @Author chenmingming
         * @Description //TODO 重新更新 下用户信息
         * @Date 20:02 2021/3/31
         * @Param []
         * @return com.ruoyi.common.lvlv.api.R<com.ruoyi.common.lvlv.api.vodto.user.UserInfoVO>
         **/
        redisCache.setCacheObject(RedisConstant.API_LOGIN_USER_TOKEN+"_"+ApiUserUtils.getToken(),businesTUser,apiConfig.getTokenExpireTime(), TimeUnit.DAYS);

        userInfoVO.setAvatarUrl(businesTUser.getAvatar());
        userInfoVO.setNickName(businesTUser.getNickName());
        userInfoVO.setPhone(businesTUser.getUserName());
        userInfoVO.setType(businesTUser.getUserType());


        return R.ok(userInfoVO,"获取个人用户信息成功");
    }

    /**
     * 保存
     *
     * @param
     * @return 结果
     */
    @ApiOperationSupport(author = "chenmingming",order = 2)
    @ApiOperation("保存头像你和昵称")
    @ResponseBody
    @LoginRequired
    @PostMapping(value = "/saveWeixinNickName")
    public R<WeiXinNickNameDTO> saveWeixinNickName(@RequestBody WeiXinNickNameDTO weiXinNickNameDTO) throws IOException {
        Set<ConstraintViolation<WeiXinNickNameDTO>> failures = validator.validate(weiXinNickNameDTO);
        if (!failures.isEmpty()) {
            return R.fail(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
        }
        /*if(StringUtils.isEmpty(weiXinNickNameDTO.getAvatarUrl())){
            weiXinNickNameDTO.setAvatarUrl("http://xili-pic.oss-cn-hangzhou.aliyuncs.com/default/ic_head_default.png");
        }*/
        final WxMaService wxService = WeixinInit.getMaService(WxConfig.lsAppId);
        //String sessionKey, String encryptedData, String ivStr
        SysUser reuser=ApiUserUtils.getBusinesTUserr();
        //判断是否有手机用户存在
        SysUser  businesTUser=apiLoginService.selectTUserById(reuser.getUserId());
        if(businesTUser!=null){
            URL url1 = new URL(weiXinNickNameDTO.getAvatarUrl());
            URLConnection uc = url1.openConnection();
            InputStream inputStream = uc.getInputStream();
// 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String fileName = MD5Util.MD5(System.currentTimeMillis() + RandomNumberGenerator.generateNumber(4))+ApiUserUtils.getBusinesTUserr().getUserName()+".jpg";
            // 设置数据缓冲
            byte[] bs = new byte[1024 * 2];
            // 读取到的数据长度
            int len = 0;
            // 输出的文件流保存图片至本地
            OutputStream os = new FileOutputStream(filePath+"/"+fileName);
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.close();
            inputStream.close();

            businesTUser.setNickName(weiXinNickNameDTO.getNickName());
            String pathFileName=FileUploadUtils.getPathFileName(filePath,fileName);
            businesTUser.setAvatar(pathFileName);
            apiLoginService.updateUserProfile(businesTUser);
            redisCache.setCacheObject(RedisConstant.API_LOGIN_USER_TOKEN+"_"+ApiUserUtils.getToken(),reuser);
            weiXinNickNameDTO.setAvatarUrl(pathFileName);
            weiXinNickNameDTO.setNickName(weiXinNickNameDTO.getNickName());
        }
        return R.ok(weiXinNickNameDTO,"保存成功");
    }
}
